{% extends "base.html" %}

{% block title %}测试套件管理 - UI自动化测试平台{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2>测试套件管理</h2>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#testSuiteModal" id="addTestSuiteBtn">
                <i class="bi bi-plus"></i> 新建测试套件
            </button>
        </div>
        
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover" id="testSuitesTable">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>名称</th>
                                <th>描述</th>
                                <th>测试用例数</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 测试套件模态框 -->
<div class="modal fade" id="testSuiteModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="testSuiteModalLabel">测试套件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="testSuiteForm">
                    <input type="hidden" id="testSuiteId">
                    <div class="mb-3">
                        <label for="testSuiteName" class="form-label">名称 *</label>
                        <input type="text" class="form-control" id="testSuiteName" required>
                    </div>
                    <div class="mb-3">
                        <label for="testSuiteDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="testSuiteDescription" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">包含的测试用例</label>
                        <div id="testCasesList">
                            <!-- 测试用例将通过JavaScript动态加载 -->
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveTestSuiteBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 执行测试套件模态框 -->
<div class="modal fade" id="executeTestSuiteModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="suiteExecutionModalLabel">执行测试套件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="suiteExecutionResult">
                    <!-- 执行结果将通过JavaScript动态加载 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 当前操作模式：'add' 或 'edit'
    var currentMode = 'add';
    
    // 加载测试套件列表
    function loadTestSuites() {
        $.get('/api/testsuites')
            .done(function(data) {
                var tbody = $('#testSuitesTable tbody');
                tbody.empty();
                
                data.forEach(function(testSuite, index) {
                    var row = `
                        <tr>
                            <td>${index + 1}</td>
                            <td>${testSuite.name}</td>
                            <td>${testSuite.description || ''}</td>
                            <td>${testSuite.test_case_ids ? testSuite.test_case_ids.length : 0}</td>
                            <td>${formatDate(testSuite.created_at)}</td>
                            <td>
                                <button class="btn btn-sm btn-primary" onclick="editTestSuite(${testSuite.id})">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-sm btn-success" onclick="executeTestSuite(${testSuite.id})">
                                    <i class="bi bi-play"></i>
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="deleteTestSuite(${testSuite.id})">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </td>
                        </tr>
                    `;
                    tbody.append(row);
                });
            })
            .fail(function() {
                alert('加载测试套件失败');
            });
    }
    
    // 重置表单
    function resetForm() {
        $('#testSuiteId').val('');
        $('#testSuiteName').val('');
        $('#testSuiteDescription').val('');
        $('#testSuiteModalLabel').text('新建测试套件');
        $('#testCasesList').empty();
    }
    
    // 加载测试用例列表（用于套件）
    function loadTestCasesForSuite() {
        return $.get('/api/testcases')
            .done(function(data) {
                var container = $('#testCasesList');
                container.empty();
                
                if (data.length === 0) {
                    container.html('<p>暂无测试用例</p>');
                    return;
                }
                
                data.forEach(function(testCase) {
                    var caseHtml = `
                        <div class="form-check">
                            <input class="form-check-input testCaseCheckbox" type="checkbox" value="${testCase.id}" id="testCase_${testCase.id}">
                            <label class="form-check-label" for="testCase_${testCase.id}">
                                ${testCase.name}
                            </label>
                        </div>
                    `;
                    container.append(caseHtml);
                });
            })
            .fail(function() {
                $('#testCasesList').html('<p>加载测试用例失败</p>');
            });
    }
    
    // 保存测试套件
    function saveTestSuite() {
        var id = $('#testSuiteId').val();
        var name = $('#testSuiteName').val();
        var description = $('#testSuiteDescription').val();
        
        if (!name) {
            alert('请输入测试套件名称');
            return;
        }
        
        // 获取所有选中的测试用例ID
        const testCaseIds = $('.testCaseCheckbox:checked').map(function() {
            return parseInt($(this).val(), 10);
        }).get();
        
        var data = {
            name: name,
            description: description,
            test_case_ids: testCaseIds
        };
        
        var method = id ? 'PUT' : 'POST';
        var urlPath = id ? '/api/testsuites/' + id : '/api/testsuites';
        
        $.ajax({
            url: urlPath,
            method: method,
            contentType: 'application/json',
            data: JSON.stringify(data)
        })
        .done(function() {
            var modal = bootstrap.Modal.getInstance(document.getElementById('testSuiteModal'));
            if (modal) {
                modal.hide();
            }
            loadTestSuites(); // 重新加载测试套件列表以更新用例数量
            showToast('保存成功');
        })
        .fail(function() {
            showToast('保存失败', 'error');
        });
    }
    
    // 编辑测试套件
    function editTestSuite(id) {
        currentMode = 'edit';
        $.get('/api/testsuites/' + id)
            .done(function(testSuite) {
                $('#testSuiteId').val(testSuite.id);
                $('#testSuiteName').val(testSuite.name);
                $('#testSuiteDescription').val(testSuite.description);
                
                // 加载测试用例并选中已关联的
                loadTestCasesForSuite().then(function() {
                    // 延迟执行以确保复选框已创建
                    setTimeout(function() {
                        // 选中已关联的测试用例
                        if (testSuite.test_case_ids) {
                            testSuite.test_case_ids.forEach(function(testCaseId) {
                                $('#testCase_' + testCaseId).prop('checked', true);
                            });
                        }
                        
                        // 设置模态框标题为"编辑测试套件"
                        $('#testSuiteModalLabel').text('编辑测试套件');
                        
                        // 显示模态框
                        var modal = new bootstrap.Modal(document.getElementById('testSuiteModal'));
                        modal.show();
                    }, 100);
                });
            })
            .fail(function() {
                alert('加载测试套件失败');
            });
    }
    
    // 删除测试套件
    function deleteTestSuite(id) {
        // 直接删除，无需确认
        $.ajax({
            url: '/api/testsuites/' + id,
            method: 'DELETE'
        })
        .done(function() {
            loadTestSuites();
            showToast('删除成功');
        })
        .fail(function() {
            showToast('删除失败', 'error');
        });
    }
    
    // 执行测试套件
    function executeTestSuite(suiteId) {
        // 显示执行中状态
        $('#suiteExecutionModalLabel').text(`执行测试套件...`);
        $('#suiteExecutionResult').html('<div class="text-center"><div class="spinner-border" role="status"></div><p>执行中...</p></div>');
        
        // 显示模态框
        var modal = new bootstrap.Modal(document.getElementById('executeTestSuiteModal'));
        modal.show();
        
        // 获取选中的浏览器
        var selectedBrowser = localStorage.getItem('selectedBrowser') || 'edge';
        
        // 调用后端执行测试套件接口
        $.ajax({
            url: '/api/testsuites/' + suiteId + '/execute',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({browser: selectedBrowser})
        })
        .done(function(result) {
            // 显示执行结果
            displaySuiteExecutionResult(result);
        })
        .fail(function(xhr) {
            // 显示错误信息
            var errorHtml = `
                <div class="alert alert-danger" role="alert">
                    <h4 class="alert-heading">执行失败</h4>
                    <p>${xhr.responseJSON ? xhr.responseJSON.error : '未知错误'}</p>
                </div>
            `;
            $('#suiteExecutionResult').html(errorHtml);
        });
    }
    
    // 显示测试套件执行结果
    function displaySuiteExecutionResult(result) {
        // 设置模态框标题
        $('#suiteExecutionModalLabel').text(`执行测试套件: ${result.test_suite ? result.test_suite.name : '未知套件'}`);
        
        // 清空结果容器
        $('#suiteExecutionResult').empty();
        
        // 显示总体结果
        var statusClass = result.status === 'PASS' ? 'success' : result.status === 'FAIL' ? 'danger' : 'warning';
        var statusText = result.status === 'PASS' ? '通过' : result.status === 'FAIL' ? '失败' : '错误';
        
        var summaryHtml = `
            <div class="card mb-3">
                <div class="card-header">
                    <h5>执行概要</h5>
                </div>
                <div class="card-body">
                    <p><strong>状态:</strong> <span class="badge bg-${statusClass}">${statusText}</span></p>
                    <p><strong>执行时间:</strong> ${(result.execution_time || 0).toFixed(2)} 秒</p>
                    <p><strong>执行时间:</strong> ${formatDate(result.executed_at)}</p>
                </div>
            </div>
        `;
        
        $('#suiteExecutionResult').append(summaryHtml);
        
        // 显示详细日志
        if (result.log) {
            var logHtml = `
                <div class="card">
                    <div class="card-header">
                        <h5>详细日志</h5>
                    </div>
                    <div class="card-body">
                        <pre class="log-content bg-light p-2 border" style="white-space: pre-wrap; word-wrap: break-word; max-height: 400px; overflow-y: auto;">${escapeHtml(result.log)}</pre>
                    </div>
                </div>
            `;
            $('#suiteExecutionResult').append(logHtml);
        }
    }
    
    // 执行单个测试用例的函数
    function executeTestCase(testCaseId) {
        // 获取选中的浏览器
        var selectedBrowser = localStorage.getItem('selectedBrowser') || 'edge';
        
        return new Promise(function(resolve, reject) {
            $.ajax({
                url: '/api/testcases/' + testCaseId + '/execute',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({browser: selectedBrowser})
            })
            .done(function(result) {
                resolve(result);
            })
            .fail(function(xhr) {
                reject(xhr);
            });
        });
    }
    
    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return '';
        var date = new Date(dateString);
        return date.toLocaleString('zh-CN');
    }
    
    // 转义HTML特殊字符
    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    $(document).ready(function() {
        // 加载测试套件列表
        loadTestSuites();
        
        // 保存测试套件
        $('#saveTestSuiteBtn').click(function() {
            saveTestSuite();
        });
        
        // 新建测试套件按钮点击事件
        $('#addTestSuiteBtn').click(function() {
            currentMode = 'add';
            resetForm();
            loadTestCasesForSuite();
        });
        
        // 页面显示时根据操作模式决定是否重置表单
        $('#testSuiteModal').on('show.bs.modal', function (event) {
            // 如果是新建模式，则重置表单
            if (currentMode === 'add') {
                resetForm();
                loadTestCasesForSuite();
            }
        });
    });
</script>
{% endblock %}